<template>
    <div>
        <NavHeader />
        <!-- 内容区域 -->
        <div class="cart-box">
            <div class="placeholder" v-if="dataSource?.list?.length === 0">
                购物车里还没有东西哦！快去添加吧~~
            </div>
            <div v-else>
                <Table
                    :showPagination="false"
                    :options="options"
                    :columns="columns"
                    :dataSource="dataSource"
                    isCheckbox="true"
                    @rowSelected="handleRowSelected"
                >
                    <!-- 图片插槽 -->
                    <template #cover="{ index, row }">
                        <div class="cover">
                            <Cover :cover="row.service.photo.url || ''"></Cover>
                        </div>
                    </template>

                    <template #category="{ index, row }">
                        {{ row.service?.category || '' }}
                    </template>

                    <template #service_point="{ index, row }">
                        {{ row.service?.service_point || '' }}
                    </template>

                    <template #car="{ index, row }">
                        <div>
                            {{ row.car?.license_plate || '' }}
                            <span>({{ row.car?.brand }})</span>
                        </div>
                    </template>

                    <template #brand="{ index, row }">
                        {{ row.car?.brand || '' }}
                    </template>

                    <template #cost="{ index, row }"> ¥ {{ row.service?.money || '' }} </template>

                    <template #op="{ index, row }">
                        <div class="op">
                            <a href="javascript:void(0);" @click="onPay('person', row)"> 购买 </a>
                        </div>
                    </template>
                </Table>
            </div>
        </div>
        <!-- 结算 -->
        <div class="calculate">
            <el-button class="cal-btn" @click="onPay('batch')"> 结算 ( {{ gross }} ) </el-button>
        </div>

        <el-dialog v-model="dialogVisible" title="结算" width="500">
            <span v-if="category === 'batch'">
                你好，一共有 {{ checkBoxService.length }} 件商品，是否确定购买服务！
            </span>
            <span v-else> 是否确定购买该服务 </span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirm"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getCartByUserId } from '@/api/home'
import {getUserInfo} from '@/api'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfo } from '../../store/index'
import { purchase } from '@/api/service'
// const userInfo = useUserInfo().userInfo
let userInfo = {}
const dialogVisible = ref(false)
const category = ref('')
// 当多选时展示费用
const gross = ref(0)

const init = async ()=> {
    const result = await getUserInfo()
    userInfo = result.data.userInfo
}
init()
// 选中了那些商品
const selectService = reactive({
    service: [], // {carId: "", serviceId: "",}
    sum: 0 // 选中商品所有的钱
})

// 复选框选中的商品
let checkBoxService = reactive([])

const dataSource = reactive({})

const getOrderDetail = async () => {
    const res = await getCartByUserId()
    if (res.status !== 200) return
    Object.assign(dataSource, res.data)
}

getOrderDetail()

const options = {
    extHeight: 100
}

// 复选框事件
const handleRowSelected = (val) => {
    checkBoxService = [...val]
    let crash = 0
    checkBoxService.forEach((item) => {
        crash += item.service.money
    })
    gross.value = crash
}

// 购买
const onPay = async (sort, row) => {
    category.value = sort
    if (checkBoxService.length === 0 && sort === 'batch') {
        return ElMessage.warning('您当前还没有选择商品，请选择商品')
    }
    if (sort === 'batch') {
        let crash = 0
        checkBoxService.forEach((item) => {
            crash += item.service.money
        })
        if (crash > userInfo.account) {
            return ElMessage.warning('您的账户不足以支付，请及时充值！')
        }
        dialogVisible.value = true
        const service = checkBoxService.map((item) => {
            return {
                carId: item.car.id,
                serviceId: item.service.id,
                cartId: item.id
            }
        })
        selectService.sum = crash
        selectService.service = service
    } else if (sort === 'person') {
        if (userInfo.account < row.service.money) {
            return ElMessage.warning('您的账户不足以支付，请及时充值！')
        }
        dialogVisible.value = true
        selectService.service = [{ carId: row.car.id, serviceId: row.service.id, cartId: row.id }]
        selectService.sum = row.service.money
    }
}

const confirm = async () => {
    try {
        // 批量购买
        const res = await purchase(selectService)
        if (res.data.code === '901') {
            return ElMessage.error('购买失败')
        }
        getOrderDetail()
    } catch (e) {
        return ElMessage.error('网络错误， 购买失败，请稍后再试')
    } finally {
        dialogVisible.value = false
    }
}

const columns = [
    {
        prop: 'service',
        label: '服务图片',
        width: 200,
        scopedSlots: 'cover',
        align: 'left'
    },
    {
        prop: 'service',
        label: '服务类型',
        scopedSlots: 'category',
        align: 'left'
    },
    {
        prop: 'service_point',
        label: '服务点',
        scopedSlots: 'service_point',
        align: 'left'
    },
    {
        prop: 'car',
        label: '车辆',
        scopedSlots: 'car',
        align: 'center'
    },
    {
        prop: 'cost',
        label: '单价',
        width: 150,
        scopedSlots: 'cost',
        align: 'center'
    },
    {
        prop: 'op',
        label: '操作',
        width: 120,
        align: 'center',
        scopedSlots: 'op'
    }
]
</script>

<style lang="scss" scoped>
.calculate {
    padding: 10px 250px;
    .cal-btn {
        background-color: green;
        float: right;
        color: #fff;
    }
}

.cart-box {
    width: 1120px;
    margin: 0 auto;

    .placeholder {
        color: #555;
        line-height: 80px;
        font-size: 24px;
    }

    .pay {
        border-top: 1px solid #ebeef5;
        padding: 15px 5px;
        overflow: hidden;
        text-align: right;
        color: #777;
        font-size: 14px;

        .btn-pay {
            display: inline-block;
            width: 120px;
            cursor: pointer;
            line-height: 36px;
            text-align: center;
            color: #fff;
            background-color: #95bf47;
            margin-left: 15px;
        }
    }

    .cover {
        display: flex;
        align-items: center;
        .cove_text {
            margin-left: 10px;
            text-overflow: ellipsis;
            overflow: hidden;
            text-wrap: nowrap;
        }
    }
}
</style>
